// 获取文章列表并渲染页面
const queryObject = {
    status: '', // 1代表审核通过，2代表待审核 ''空字符串代表全部
    channel_id: '', // 文章频道id，''空字符串代表全部
    page: 1, // 当前页码
    per_page: 2 // 每页显示数据条数
}
let totalCount = 0

async function getArticleList() {
    try {
        const success = await axios({
            url: '/v1_0/mp/articles',
            params: queryObject
        })
        console.log(success)
        totalCount = success.data.total_count
        document.querySelector('.content-body-article').innerHTML = success.data.results.map(item => {
            const {title, status, pubdate, comment_count, read_count, like_count, id} = item
            const {type, images} = item.cover
            return `
                <ul>
			    	<li><a href="javascript:"><img alt="" src=${type === 0 ? `../../assets/images/default.jpg` : images}></a></li>
			    	<li><a href="javascript:" title="${title}">${title}</a></li>
			    	<li>
			    	    ${status === 1 ? `<i class="pending-review">待审核</i>` : `<i class="approved">审核通过</i>`}			    					   
			    	</li>
			    	<li>${pubdate}</li>
			    	<li>${read_count}</li>
			    	<li>${comment_count}</li>
			    	<li>${like_count}</li>
			    	<li>
			    		<a class="icon-trash5 delete" href="javascript:" data-id="${id}" data-bs-toggle="modal" data-bs-target="#deleteModal"></a>
			    		<a class="icon-edit2 edit" href="javascript:" data-id="${id}"></a>
			    	</li>
			    </ul>
            `
        }).join('')
        document.querySelector('.total-page em').innerHTML = totalCount
    } catch (error) {
        console.log(error)
    }
}

getArticleList()

// 监听单选框改变事件
document.querySelectorAll('.content-manage-state input').forEach(radio => radio.addEventListener('change', e => queryObject.status = e.target.value))

// 监听频道列表改变事件
document.querySelector('.channel').addEventListener('change', e => queryObject.channel_id = e.target.value)

// 筛选
document.querySelector('.screen').addEventListener('click', () => {
    getArticleList()
})

// 分页功能
document.querySelector('.page-next').addEventListener('click', () => {
    if (queryObject.page < Math.ceil(totalCount / queryObject.per_page)) {
        queryObject.page++
        document.querySelector('.current-page em').innerHTML = queryObject.page
        getArticleList()
    }
})

document.querySelector('.page-pre').addEventListener('click', () => {
    if (queryObject.page > 1) {
        queryObject.page--
        document.querySelector('.current-page em').innerHTML = queryObject.page
        getArticleList()
    }
})

// 删除功能
// 创建删除文章弹框对象
const deleteModal = new bootstrap.Modal(document.querySelector('#deleteModal'))
document.querySelector('.content-body-article').addEventListener('click', e => {
    if (e.target.classList.contains('delete')) {
        document.querySelector('.confirm').addEventListener('click', function () {
            axios({
                url: `/v1_0/mp/articles/${e.target.dataset.id}`,
                method: 'DELETE',
            }).then(success => {
                // 删除最后一页，最后一条数据时，需要当前页自动向前翻页
                const children = document.querySelector('.content-body-article').children
                if (children.length === 1 && queryObject.page !== 1){
                    queryObject.page--
                    document.querySelector('.current-page em').innerHTML = queryObject.page
                }
                getArticleList()
                deleteModal.hide()
            })
        })
    }
})

// 点击编辑时，获取文章id，跳转到修改文章页面
document.querySelector('.content-body-article').addEventListener('click',async e => {
    if (e.target.classList.contains('edit')){
        location.href = `../publish/index.html?id=${e.target.dataset.id}`
    }
})

// 点击退出按钮时，返回登录页面
const quitModal = new bootstrap.Modal(document.querySelector('#quitModal'))
document.querySelector('.quit-confirm').addEventListener('click',function (e) {
    localStorage.removeItem('token')
    getAlert(document.querySelector('.manage-alert'),'正在退出系统...',true)
    setTimeout(function () {
        location.href = '../login/index.html'
    },1000)
    quitModal.hide()
})